// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import store from './store/store'
import axios from 'axios'
import vueAxios from 'vue-axios'
import VueCookies from 'vue-cookies';

Vue.use(VueCookies)
Vue.use(ElementUI)
Vue.config.productionTip = false
Vue.use(vueAxios, axios)
axios.defaults.timeout = 5000;// 请求超时
axios.defaults.baseURL = process.env.URL;
axios.defaults.headers.post['Content-Type'] = 'application/json';

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: {App},
  template: '<App/>',
  store
})

// 添加请求拦截器，在请求头中加token,Cookie
axios.interceptors.request.use(
  config => {
    if (localStorage.getItem('Authorization')) {
      config.headers.Authorization = localStorage.getItem('Authorization');
    }
    if (localStorage.getItem('Cookies')) {
      config.headers.Cookies = localStorage.getItem('Cookies');
    }
    return config;
  }, error => {
    return Promise.reject(error);
  });

// 这里拦截401错误，并重新跳入登页重新获取token
axios.interceptors.response.use(
  response => {
    console.log("response.use" + response)
    if (response.data.data && response.data.data.ecode == '401') {
      localStorage.removeItem('Authorization');
      localStorage.removeItem('Cookies');
      this.$router.push('/login');
    } else {
      return response;
    }
  }, error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          localStorage.removeItem('Authorization');
          localStorage.removeItem('Cookies');
          this.$router.push('/login');
      }
    }
    return Promise.reject(error.response.data)
  }
);
